package cn.sylinx.horm.proxy.command.invoker;

import java.util.Map;

import cn.sylinx.horm.core.SqlClient;
import cn.sylinx.horm.proxy.command.CommandMethodMetadata;
import cn.sylinx.horm.resource.ClasspathSqlResource;
import cn.sylinx.horm.util.Tuple;

class ObjectListCommandInvoker extends AbstractCommandInvoker {

    @Override
    public Object invoke(CommandMethodMetadata methodMetadata, Tuple tuple) {
        Map<String, Object> params = tuple.getObject(0);
        String truelyDatasource = tuple.getObject(3);
        String nativeSql = methodMetadata.getResource().nativeSql();
        Class<?> truelyReturnType = methodMetadata.getTruelyReturnType();
        String sql = methodMetadata.getResource().sql();
        SqlClient ormClient = getClient(truelyDatasource);
        String parseSqlType = getParseSqlType(methodMetadata.getResource().parseSqlType());

        // 使用native sql
        boolean isNativeSql = nativeSql != null && !nativeSql.trim().isEmpty();
        if (isNativeSql) {
            Tuple t = ormClient.parseSql(nativeSql, parseSqlType, params);
            String truelyNativeSql = t.getObject(0);
            Object[] truelyParams = t.getObject(1);
            return ormClient.queryListForSingleColumn(truelyNativeSql, truelyParams, truelyReturnType);
        }

        return ormClient.queryListForSingleColumn(new ClasspathSqlResource(sql, parseSqlType), params,
                truelyReturnType);
    }
}
